import 'package:amway_superapp_creator_plugin/analysis/zhuge_circle.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/models/haowu_product_models.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/colors_util.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/circle/related_shop_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../base_view.dart';

class ShopCategory extends StatefulWidget {
  List<HaowuProduct> chosenList;

  ShopCategory({Key key, this.chosenList}) : super(key: key);

  @override
  _ShopCategoryState createState() => _ShopCategoryState();
}

class _ShopCategoryState extends State<ShopCategory>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BaseView(
        model: RelatedShopModel(api: Provider.of(context)),
        onModelReady: (model) async {
          if (widget.chosenList != null && widget.chosenList.isNotEmpty) {
            widget.chosenList.forEach((element) {
              element.isChecked = true;
            });
          }
          model.getCategoryList();
        },
        builder: ((context, model, child) => Scaffold(
              backgroundColor: Colors.white,

              appBar: AppBar(
                leading: IconButton(
                    onPressed: () {
                      Application.router.pop(context);
                    },
                    icon: Icon(
                      Icons.arrow_back_ios,
                      color: ColorsConfig.c_2c2c2c,
                    )),
                title: Text(
                  "选择商品",
                  style: TextStyle(
                      color: ColorsConfig.c_2c2c2c,
                      fontSize: ScreenUtil().setSp(20),
                      fontWeight: FontWeight.bold),
                ),
                centerTitle: true,
                backgroundColor: Colors.white,
                elevation: 0,
                //去除阴影
                brightness: Brightness.light,
                //黑色状态栏
              ),
              body:
                  Row(children: [_left(model), _right(model, model.position)]),
              bottomNavigationBar: _success(model),
            )));
  }

/*
* 左侧导航
* */
  Widget _left(RelatedShopModel model) {
    return Container(
      width: ScreenUtil().setWidth(120),
      height: double.maxFinite,
      color: ColorUtil.fromHex('#727272').withOpacity(0.05),
      child: ListView.builder(
          shrinkWrap: true,
          itemCount: model.category.length,
          itemBuilder: (context, index) {
            return _leftItem(model, index);
          }),
    );
  }

  Widget _leftItem(RelatedShopModel model, int index) {
    return InkWell(
        onTap: () {
          model.isChecked(index);
        },
        child: Container(
          //水平居左显示
          alignment: Alignment.centerLeft,
          height: ScreenUtil().setWidth(60),
          padding: EdgeInsets.only(left: ScreenUtil().setWidth(15)),
          color: model.category[index].isChecked != null &&
                  model.category[index].isChecked
              ? Colors.white
              : ColorsConfig.c_f8f8f8,
          child: Row(
            children: [
              model.category[index].isChecked != null &&
                      model.category[index].isChecked == true
                  ? Container(
                      margin: EdgeInsets.only(right: ScreenUtil().setWidth(6)),
                      color: ColorsConfig.c_396E75,
                      width: ScreenUtil().setWidth(2),
                      height: ScreenUtil().setWidth(15),
                    )
                  : Container(),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Text(
                  model.category[index].categoryName == null
                      ? ""
                      : model.category[index].categoryName,
                  style: model.category[index].isChecked != null &&
                          model.category[index].isChecked == true
                      ? TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: ScreenUtil().setSp(16),
                          color: ColorsConfig.c_2c2c2c,
                        )
                      : TextStyle(
                          fontSize: ScreenUtil().setSp(16),
                          color: ColorsConfig.c_2c2c2c,
                        ),
                ),
              )
            ],
          ),
        ));
  }

  Widget _right(RelatedShopModel model, int position) {
    return Expanded(
        child: Container(
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 0,
            mainAxisSpacing: ScreenUtil().setHeight(16),
            childAspectRatio: 120 / 105),
        itemCount: model.category.length == 0
            ? 0
            : model.category[position].childNavigationNode != null
                ? model.category[position].childNavigationNode.length
                : 0,
        itemBuilder: (BuildContext context, int index) {
          return _rightItem(model, position, index);
        },
        padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(16),
            ScreenUtil().setHeight(21), ScreenUtil().setWidth(16), 0),
      ),
    ));
  }

  Widget _rightItem(RelatedShopModel model, int position, int index) {
    String pictureUrl = "";
    String categoryImage = "";
    if (model.category[position].childNavigationNode != null &&
        model.category[position].childNavigationNode[index] != null) {
      StringBuffer buffer = new StringBuffer();
      buffer.write(OssHelper.pictureBaseUrl);
      buffer.write(
          model.category[position].childNavigationNode[index].childNodeIcon);
      pictureUrl = buffer.toString();
    }
    if (model.category[position].categoryImage != null &&
        model.category[position].categoryImage.isNotEmpty) {
      StringBuffer buffer = new StringBuffer();
      buffer.write(OssHelper.pictureBaseUrl);
      buffer.write(model.category[position].categoryImage);
      categoryImage = buffer.toString();
    }

    return SingleChildScrollView(
      child: InkWell(
        child: Column(children: [
          Image.network(
            index == 0 ? categoryImage : pictureUrl,
            width: ScreenUtil().setWidth(71),
            height: ScreenUtil().setWidth(71),
            fit: BoxFit.fill,
          ),
          Container(
            child: Text(
              model.category[position].childNavigationNode != null &&
                      model.category[position].childNavigationNode[index] !=
                          null
                  ? model.category[position].childNavigationNode[index]
                      .childNodeName
                  : "",
              overflow: TextOverflow.ellipsis,
              softWrap: true,
              style: TextStyle(
                  color: ColorsConfig.c_802c2c2c,
                  fontSize: ScreenUtil().setSp(14)),
            ),
            margin: EdgeInsets.only(top: ScreenUtil().setHeight(3)),
          )
        ]),
        onTap: () {
          var linkCode =
              model.category[position].childNavigationNode[index].childNodeLink;
          Map<String, dynamic> parameters = {
            'title':
                "${model.category[position].categoryName} - ${model.category[position].childNavigationNode[index].childNodeName}",
            'code': index == 0
                ? model.category[position].childNavigationNode[index].code
                : linkCode.substring(
                    linkCode.lastIndexOf("=") + 1, linkCode.length),
            'list': widget.chosenList != null && widget.chosenList.isNotEmpty
                ? widget.chosenList
                : null
          };
          Application.router
              .navigateTo(context, Routes.shoplist,
                  routeSettings: RouteSettings(arguments: parameters))
              .then((value) {
            List<HaowuProduct> list = value;
            if (list != null && list.isNotEmpty) {
              widget.chosenList = list;
            }
          });
        },
      ),
    );
  }

  Widget _success(RelatedShopModel model) {
    return Container(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(16),
            ScreenUtil().setWidth(16),
            ScreenUtil().setWidth(16),
            ScreenUtil().setWidth(34)),
        decoration: new BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
                color: ColorUtil.fromHex('#26000000'),
                offset: Offset(0, -ScreenUtil().setHeight(2)),
                blurRadius: ScreenUtil().setHeight(15))
          ],
        ),
        child: Container(
            width: double.infinity,
            height: ScreenUtil().setWidth(50),
            child: RaisedButton(
              color: Color(0xff396E75),
              highlightColor: Color(0xD4396E75),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25)),
              onPressed: () {
                List<String> list = [];
                widget.chosenList.forEach((element) {
                  list.add(element.skuCode);
                });
                ZhugeCircleAnalysis.circleAddGoodsSave("选择商品", list);
                Application.router.pop(context, widget.chosenList);
              },
              child: Text(
                "完成",
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(18)),
              ),
            )));
  }
}
